package com.example.mvvmtest.viewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.mvvmtest.Repository.UserRepository
import kotlinx.coroutines.launch

class LoginActivityViewModel(override val userRepository: UserRepository) : UserViewModel(userRepository) {

    // 表单数据
    private val _id = MutableLiveData("")
    val id: LiveData<String> = _id

    private val _password = MutableLiveData("")
    val password: LiveData<String> = _password

    // 状态
    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _loginSuccess = MutableLiveData<Boolean?>(null)
    val loginSuccess: LiveData<Boolean?> = _loginSuccess  // null:初始, true:成功, false:失败

    private val _errorMessage = MutableLiveData("")
    val errorMessage: LiveData<String> = _errorMessage

    // 更新输入
    fun onIdChanged(id: String) {
        _id.value = id
        _errorMessage.value = ""
    }

    fun onPasswordChanged(password: String) {
        _password.value = password
        _errorMessage.value = ""
    }

    // 登录逻辑
    fun login() {
        val id = _id.value?.trim() ?: ""
        val password = _password.value?.trim() ?: ""

        when {
            id.isEmpty() -> _errorMessage.value = "账号不能为空"
            password.isEmpty() -> _errorMessage.value = "密码不能为空"
            else -> {
                viewModelScope.launch {
                    _isLoading.value = true
                    try {
                        val user = userRepository.checkLogin(id, password)
                        if (user != null) {
                            _loginSuccess.value = true  // 登录成功
                        } else {
                            _errorMessage.value = "账号或密码错误"
                            _loginSuccess.value = false
                        }
                    } catch (e: Exception) {
                        _errorMessage.value = "登录失败: ${e.message}"
                        _loginSuccess.value = false
                    } finally {
                        _isLoading.value = false
                    }
                }
            }
        }
    }

    fun resetLoginState() {
        _loginSuccess.value = null
    }
}